import { ref, onMounted, onUnmounted, Ref } from 'vue'
/**
 * 是否点击到目标下拉框以外的区域
 * @param elementRef node 节点
 */
const useClickOutside = (elementRef: Ref<null | HTMLElement>) => {
  const isClickOutside = ref(false) // 是否点击下拉框外面
  const handler = (e: MouseEvent) => {
    // 判断节点是否存在
    if (elementRef.value) {
      // web api - node.contains 用于检查一个节点是否是另一个节点的后代
      // 点击元素是否是下拉框元素的子级
      if (elementRef.value.contains(e.target as HTMLElement)) {
        isClickOutside.value = false
      } else {
        isClickOutside.value = true
      }
    }
  }
  onMounted(() => {
    document.addEventListener('click', handler)
  })
  onUnmounted(() => {
    document.removeEventListener('click', handler)
  })
  return isClickOutside
}

export default useClickOutside
